const express = require('express');
const compression = require('compression');
// 登录注册模块
const {
	router: userRouter
} = require('./router/user.js');
// 我的详情模块
const {
	router: userInfoRouter
} = require('./router/userInfo.js');
// 文章分类模块
const {
	router: artCateRouer
} = require('./router/artcate.js');
// 文章模块
const {
	router: articleRouter
} = require('./router/article.js');
// 处理响应
const {
	sendError
} = require('./tools/sendFunction.js');

const app = express();

// 处理token
const expjwt = require('express-jwt');


// 解决跨域问题
app.use((req, res, next) => {
	res.setHeader('Access-Control-Allow-Origin', '*');
	res.setHeader('Access-Control-Allow-Methods', '*');
	res.setHeader('Access-Control-Allow-Credentials', true);
	res.setHeader('Access-Control-Allow-Headers', '*');
	next();
})

app.use(compression());
app.use(express.static('public'));

// 静态资源托管
app.use('/uploads', express.static('uploads'));

// 加密字符串
let str = 'secret';
// 解析token
app.use(expjwt({
	secret: str,
	algorithms: ["HS256"]
}).unless({
	path: [/^\/api\//]
}));

// 配置接收post请求参数
app.use(express.json());
app.use(express.urlencoded({
	extended: false
}));

app.use('/api', userRouter);
app.use('/my', userInfoRouter);
app.use('/my/artcate', artCateRouer);
app.use('/my/article', articleRouter);

app.get('/',(req,res)=>{
	res.redirect('/index.html');
})

// 错误处理中间件
app.use((err, req, res, next) => {
	// token错误
	if (err.message == 'No authorization token was found' || err.message == 'invalid token' || err.message == 'jwt expired') {
		sendError(res, 403, '身份认证失败,请重新登录!');
	} else {
		sendError(res, 400, err.message);
	}
})

app.listen(3000);
console.log('服务器启动成功');